package com.onjob.photo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.onjob.employment.PersonInfoDao;
import com.onjob.employment.Resume;
import com.onjob.employment.ResumeAction;
import com.onjob.employment.ResumeDao;
import com.opensymphony.xwork2.ActionSupport;

public class PhotoAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Photo photo;
	private PhotoDao photoDao;
	private Resume resume;
	private ResumeDao resumeDao;
	private PersonInfoDao personInfoDao;
	private File photofile;
	public Photo getPhoto() {
		return photo;
	}

	public void setPhoto(Photo photo) {
		this.photo = photo;
	}

	public void setPhotoDao(PhotoDao photoDao) {
		this.photoDao = photoDao;
	}

	public Resume getResume() {
		return resume;
	}

	public void setResume(Resume resume) {
		this.resume = resume;
	}

	public void setResumeDao(ResumeDao resumeDao) {
		this.resumeDao = resumeDao;
	}

	public String upload() throws Exception {
		
		this.resume.setDate(new Date());
		this.resume.setPersonInfo(this.personInfoDao
				.findById(ServletActionContext.getRequest().getSession()
						.getAttribute("personInfoid").toString()));
		this.resumeDao.saveOrUpdate(this.resume);
		ServletActionContext.getRequest().getSession().setAttribute(
				"resumeid",
				this.resumeDao.findResumeByTypes(this.resume.getName(),(ServletActionContext.getRequest().getSession()
						.getAttribute("personInfoid").toString()), "name","personInfo.id")
						.getId());
		
		if(null != this.photofile){
			this.photo.setFile(this.getPhotofile());
			InputStream input = new FileInputStream(this.photo.getFile());
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int b = 0;
			while ((b = input.read()) != -1)
				baos.write(b);
			
			this.photo.setDate(baos.toByteArray());
			this.photo.setResumeId((this.resumeDao.findById(ServletActionContext
					.getRequest().getSession().getAttribute("resumeid").toString())));
			
			
			this.photoDao.create(this.photo);
		}
		
		return SUCCESS;
	}

	public void setPersonInfoDao(PersonInfoDao personInfoDao) {
		this.personInfoDao = personInfoDao;
	}

	public File getPhotofile() {
		return photofile;
	}

	public void setPhotofile(File photofile) {
		this.photofile = photofile;
	}

}
